import mc
import xbmc
import urllib
import sage
import config
from sage import SageApi, SageApiException
import epg
import conflicts
try:
	import version
except:
	mc.LogDebug("SageBoxee: Exception accessing version.py.")
	mc.ShowDialogOk("Application can't be started.","The file 'version.py' is missing or corrupt.")
	exit(0)
	
def makeNonNone(a):
	if a == None:
		return ''
	else:
		return a

try:
	import jettydefaults
	haveCreds = True
	mc.LogDebug("SageBoxee: Found default jetty credentials.")
except:
	mc.LogDebug("SageBoxee: Did not find default jetty credentials.")
	haveCreds = False
	
config.initialize()

if haveCreds:
	config.setMediaPathMaps(jettydefaults.uncMap)
	
# Make sure server, jetty user name and jetty password are non-empty.
if haveCreds:
	server = jettydefaults.server
else:
	server = config.getSageServer()

# A null value means the user has not configured the parameter.  A value of 'None' means the user has configured the parameter
# to None
if server == 'None':
	server = None
elif len(server)==0:
	server = mc.ShowDialogKeyboard("Enter Sage server IP:port. Eg 192.168.1.121", "", False)
	if server == None or server == '':
		config.setSageServer('None')
		server = None
	else:
		config.setSageServer(server)

if haveCreds:
	jettyname = jettydefaults.jettyname
else:
	jettyname = config.getJettyUser()

if jettyname == 'None':
	jettyname = None
elif len(jettyname)==0:
	jettyname = mc.ShowDialogKeyboard("Enter user name:", "", False)
	if jettyname == None or jettyname == '':
		config.setJettyUser('None')
		jettyname = None
	else:
		config.setJettyUser(jettyname)

if haveCreds:
	jettypassword = jettydefaults.jettypassword
else:
	jettypassword = config.getJettyPassword()

if jettypassword == 'None':
	jettypassword = None	
elif len(jettypassword)==0:
	jettypassword = mc.ShowDialogKeyboard("Enter password:", "", True)
	if jettypassword == None or jettypassword == '':
		config.setJettyPassword('None')
		jettypassword = None
	else:
		config.setJettyPassword(jettypassword)

while len(config.getRawUseSSL())==0:
	response = mc.ShowDialogKeyboard("Use SSL? (y or n):", "N", False)
	mc.LogDebug("SageBoxee: UseSsl reponse = " + makeNonNone(response))
	response = response.lower()
	if response=='y' or response=='yes':
		config.setUseSSL('True')
	elif response=='n' or response=='no':
		config.setUseSSL('False')

useSsl = config.getUseSSL()
	
mc.LogDebug("SageBoxee: Credentials = " + makeNonNone(server) + ":" + makeNonNone(jettyname) + ":" + makeNonNone(jettypassword) + ":" + str(makeNonNone(useSsl)))
	
# Create the global sageAPI object and check that the server is alive.
try:
	sageAPI = SageApi(server, jettyname, jettypassword, useSsl)
except:
	mc.LogDebug("SageBoxee; Fatal error creating sageAPI. Resetting jetty creds.")
	mc.ShowDialogOk("Error","There was an error connecting to the server.  The servername, userid and password have been reset.")
	config.setSageServer('')
	config.setJettyUser('')
	config.setJettyPassword('')
	config.setUseSSL('')
	exit(1)

try:
	if not sageAPI.isApiServerAlive():
		startAnyway = mc.ShowDialogConfirm("The server could not be reached.", server + " could not be reached using the given user name and password. [CR][CR]Do you want to continue anyway?", "No", "Yes")
		print "SageBoxee: startAnyway="+str(startAnyway)
		if not startAnyway:
			exit(1)
except:
	mc.LogDebug("SageBoxee; Fatal error in isApiServerAlive(). Resetting jetty creds.")
	mc.ShowDialogOk("Error","There was an error connecting to the server.  The servername, userid and password will be reset.")
	config.setSageServer('')
	config.setJettyUser('')
	config.setJettyPassword('')
	exit(1)
	
sageVersion = sage.getSageVersion(sageAPI)
print "SageBoxee: Current Sage server version = " + sageVersion

try:
	minSageVersion = version.minsagever
except:
	mc.LogDebug("SageBoxee: Exception accessing minsagever.")
	mc.ShowDialogOk("Application can't be started.","The file 'version.py' is missing 'minsagever'.")
	exit(0)
	
print "SageBoxee: Minimum Sage server version = " + minSageVersion
if sage.comparePluginVersions(sageVersion, minSageVersion) < 0:
	mc.LogDebug("SageBoxee: Sage server below minimum version.")
	mc.ShowDialogOk("Application can't be started.","The Sage server must be upgraded to version " + minSageVersion + " or greater.")
	exit(0)

# Global dictionary used by Recordings menu to store grouped shows.
gRecordingsGroups = {}

# Global var used by Recordings menu to keep track of what show is focused in left pane.
gRecordingsFocusedShow = 0

# Global var used by EPG to keep track of the time in focus.  Will be SECONDS since epoch.  Keep in mind that the Sage APIs take ms.
gEpgTime = 0

gTopChannelIndex = 0
gAllChannelListItems = mc.ListItems()
gCurrentAiringListItems = mc.ListItems()

# Global var used by Favorites to keep track of the favorite in focus.
gFavoritesFocusedFav = 0

# Global dict used to pass parameters between windows and dialogs.
gDialogParams = {}

# Global var used to store channel Objects for purposes of watching Live TV.
gLiveTvChannels = None

# Global var used to keep track of the index within gLiveTvChannels of the last viewed channel.
gLiveTvLastChannel = 0

# Global var used to make sure OSD is not manually closed.
gKeepOSDOpen = True

# Global var used to keep track of the last action the user took when watching live TV.
gLiveTvAction = ''

# Global var used to keep track of if live tv is paused.
gLiveTvIsPaused = False

# Launch the main window.
mc.LogDebug("SageBoxee: Launching main window.")
mc.ActivateWindow(14000)

# Launch status icon updater thread. First check if an existing thread is running.
#
# t.setKeepAlive(False) stops the thread.
# t.setActiveWindow(int) tells the thread which window to update.
statusUpdater = sage.getRunningThread('SageBoxeeIconStatus')
if statusUpdater != None:
	mc.LogDebug("SageBoxee: Detected a running IconStatusThread.")
else:
	mc.LogDebug("SageBoxee: Did not detect a running IconStatusThread.")
	statusUpdater = sage.IconStatusThread(sageAPI)
	statusUpdater.start()
	statusUpdater.setName('SageBoxeeIconStatus')
statusUpdater.setActiveWindow(14000)

# Launch the conflict detection thread if it's not running already.
conflictDetector = sage.getRunningThread('SageBoxeeConflictDetection')
if conflictDetector != None:
	mc.LogDebug("SageBoxee: Detected a running ConflictDetectionThread.")
else:
	mc.LogDebug("SageBoxee: Did not detect a running ConflictDetectionThread.")
	conflictDetector = conflicts.ConflictDetectionThread(sageAPI)
	conflictDetector.start()
	conflictDetector.setName('SageBoxeeConflictDetection')
	

# Check the version of the required Sage plugins.
def getPluginVersion(plugins, ID):
	for plugin in plugins:
		if plugin['PluginIdentifier'] == ID:
			return plugin['PluginVersion']
	return None
	
allPlugins = sageAPI.GetInstalledPlugins()

for plugin in ('jetty', 'sagex-api', 'sagex-api-services'):
	print "SageBoxee: Plugin %s" % plugin
	#expr = 'GetPluginVersion(GetAvailablePluginForID("%s"))' % plugin
	#thisVersion = sageAPI.EvaluateExpression(expr)
	thisVersion = getPluginVersion(allPlugins, plugin)
	print "SageBoxee: Installed version %s" % thisVersion
	print "SageBoxee: Min version %s" % version.minplugins[plugin]
	
	if sage.comparePluginVersions(thisVersion, version.minplugins[plugin]) < 0:
		mc.LogDebug("SageBoxee: Plugin below minimum version.")
		command = 'Window.SetProperty(pluginName, %s)' % plugin
		xbmc.executebuiltin(command)
		mc.ActivateWindow(14005)
		exit(0)

#expr = 'ExecuteProcessReturnOutput("cmd", "dir", null, true, true)'
#sageAPI.EvaluateExpression(expr)

#bxe_mcc = mc.GetApp().GetLocalConfig()
#location = xbmc.executehttpapi("getguisetting(3,videoplayer.editdecision)").replace( "<li>", "" ).split(" - ")[1]	
#location = xbmc.executehttpapi("getguisetting(1,videoplayer.editdecision)")
#print "SAGEBOXEE: LOCATION BEFORE = " + str(location)
#xbmc.executehttpapi("setguisetting(1,videoplayer.editdecision,false)")
#location = xbmc.executehttpapi("getguisetting(1,videoplayer.editdecision)")
#print "SAGEBOXEE: LOCATION AFTER = " + str(location)
